package pos.presentation;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.eclipse.jdt.internal.compiler.ast.ThisReference;

import pos.domain.*;

public class FrontController extends HttpServlet {


	public void init() throws ServletException {
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		if (logado(request)) {
			String resource = request.getParameter("res");
			RequestDispatcher d = request.getRequestDispatcher(resource);
			if(d!=null){
				d.forward(request,response);
			}
			System.out.println("LOGADO ACCEDIENDO A " + resource);
		} else {
			response.sendRedirect("error.html");
			System.out.println("no logado");
		}

	}

	private boolean logado(HttpServletRequest request) {
		boolean logado = false;

		HttpSession session = request.getSession(false);

		String userForm = request.getParameter("user");
		String passwdForm = request.getParameter("passwd");

		if (session == null) {
			session = request.getSession();
			if ((userForm == null || passwdForm == null
					|| userForm.length() == 0 || passwdForm.length() == 0)) {
				if( !request.getParameter("res").equals("AltaUsuario.jsp"))
				logado = false;
				else
					logado=true;

			} else {
				if (valido(userForm, passwdForm) || request.getParameter("res").equals("AltaUsuario.jsp") ) {
					logado = true;
					session.setAttribute("session.user", userForm);
				} else {
					logado = false;
				}

			}

		} else {
			if (userForm == null || passwdForm == null) {
				logado = true;
			} else {
				if (valido(userForm, passwdForm)|| request.getAttribute("res").equals("AltaUsuario.jsp")) {
					logado = true;
					session.setAttribute("session.user", userForm);
				} else {
					logado = false;
				}

			}
		}
		return logado;
	}
//controlamos si es un usuario valido en nuestro sistema

	public boolean valido(String userForm, String passwdForm) {
		boolean res = false;
		User u = new User();
		IUserManager us = new UserManager();
		u=us.getUser(userForm);
		if(u!=null){
			res=u.getPassword().equals(passwdForm);
		}
		return res;

	}
/*
	public boolean valido(String userForm, String passwdForm) {
		boolean res = false;
		if(userForm.equals(this.user)&& passwdForm.equals(this.psswd))
			res=true;
		return res;
	}
	*/
}